// 异步操作
const buy = (url)=> new Promise((resolve,reject)=>{
  // const time = Math.random*1000;
  // setTimeout(()=>{
  //   resolve(time);
  // },time);
  // fetch h5  axios
  // h5新增的api 图片异步加载 就可以用new的方式创建图片实例
  const img = new Image();
  img.width='100';
  img.onload = function(){
    console.log('一张图片加载完成');
    resolve();
    document.body.appendChild(img);
  };
  img.error = reject;
  img.src = url;
});


// buy.then(res)

const urls = [
  'https://i.ytimg.com/vi/Lq-PeGduJYU/maxresdefault.jpg',
  'http://image.hnol.net/c/2015-12/28/14/201512281431439715-1559530.jpg',
  'https://www.198198.xyz/2020/04/14/3ff88b383bfa3.jpg',
  'https://images2.imgbox.com/2a/a7/k9bATDoY_o.jpg',
  'https://farm6.staticflickr.com/5744/30265416292_fdbc28fea1_o.jpg',
  'https://farm1.staticflickr.com/783/26447214447_7b2f0b3967_o.jpg',
  'http://pic.xxpicxx.xyz/images/jlksxklxka/9884820/20160909153220691-2089977.jpg',
  'https://images2.imgbox.com/16/ee/ucNk651i_o.jpg',
  'https://goddess247.com/wp-content/uploads/2021/05/Ugirls-App%E5%B0%A4%E6%9E%9C%E5%9C%88-No.2062-%E5%A8%9C%E9%9C%B2Selena-026.jpg',
  'https://i.xingming.com/wen/201903/2916/03.jpg',
  'https://i3.imageban.ru/out/2018/05/11/983ead86bcdcc4521c6a914b304fe209.jpg',
  'https://uploadfile.bizhizu.cn/2015/0512/20150512024636861.jpg.220.146.jpg',
  'https://avatars.mds.yandex.net/i?id=17175b3d7eaaff9b9fe8d39cad862bb7-4824023-images-thumbs&n=13&exp=1',
  'https://i.imgur.com/7Ma5Bg8.jpg',
  'http://fs2.directupload.net/images/150910/k9x4wwja.jpg',
  'https://i.ytimg.com/vi/9F91ZVroTP0/maxresdefault.jpg',
  'https://img-blog.csdnimg.cn/20191202111542767.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIxMzgzNDM1,size_16,color_FFFFFF,t_70',
  'https://1.bp.blogspot.com/-rcNBV-T2NY0/XNU97tU7QsI/AAAAAAAAppI/kgDWWC8C_nosvmIJEV9X3G4pc70j2-z_ACLcBGAs/s1600/_yoon_ju_50525740_2308121019206515_7076047022319978762_n.jpg',
  'https://ilarge.lisimg.com/image/17506508/1118full-cecil-kishimoto.jpg',
  'https://static.zuixingzuo.net/image/201812/286368161445171440523870085.jpg',
  'https://www.haixiutv.com/yl/uploadfile/2016/1025/20161025070649187.jpg',
  'https://www.haixiutv.com/yl/uploadfile/2017/0205/20170205035609193.jpg',
  'http://i1.ytimg.com/vi/HwESFWP4Sc8/maxresdefault.jpg',
];

function sendRequest(urls,max,callback){
  let count = 0;
  // 只要进入到这个方法 就准备请求
  function imgLoad (){
    count++; // 1  2  3
    console.log('并发数',count);
    // 吞吐量
    if(count<=max&&urls.length>0){
      buy(urls.shift()).then(()=>{
      // 此时一张图片就加载完了
        count--;
        urls.length<=0 && --max <= 0 && callback();
      }).then(imgLoad);
    }
  }
  for(let i = 0;i<max;i++){
    imgLoad();
  }
}

// 6以下  浏览器 最大并法量是6 http1.1协议  node 是没有限制的
sendRequest(urls,3,()=>{
  console.log('全部加载完成');
});